package edu.xhu.kafkaproducer.controller;

import cn.hutool.json.JSONUtil;
import edu.xhu.kafkaproducer.dtos.MessageDto;
import edu.xhu.kafkaproducer.enums.KafkaTopic;
import edu.xhu.model.common.dtos.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

@Api(value = "kafka-producer-test", tags = "kafka-producer-test")
@RestController
@RequestMapping("/kafka")
@Slf4j
public class KafkaProducerController {
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @PostMapping(value = "/produce", produces = "application/json")
    @ApiOperation("kakfa发送消息测试")
    public ResponseResult<?> produce(@RequestBody MessageDto messageDto) {

        try {
            String obj2String = JSONUtil.toJsonStr(messageDto);
            kafkaTemplate.send(KafkaTopic.BILL_TEST_TOPIC, obj2String);
            return ResponseResult.okResult("发送消息成功");
        } catch (Exception e) {
            e.getMessage();
            return ResponseResult.errorResult(400, e.getMessage());
        }
    }
}
